from rest_framework import serializers
from apps.oaauth.models import OADepartment
from apps.oaauth.serializers import UserSerializer,DepartmentSerialize
from .models import Inform,InformRead


class InformReadSerialize(serializers.ModelSerializer):
    class Meta:
        model = InformRead
        fields = '__all__'

class InformSerialize(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    departments = DepartmentSerialize(many=True,read_only=True)
    # public = serializers.CharField(read_only=True)
    # department_id 表示接收一个列表
    # 如果后端接收一个列表 使用ListField字段
    department_ids = serializers.ListField(write_only=True)

    # read_only不会校验这个字段的数据 而只是会将这个数据序列化成字典
    reads = InformReadSerialize(many=True,read_only=True)

    class Meta:
        model = Inform
        fields = '__all__'
        read_only_fields = ('public',)

    # post方法
    # 重写Info对象里面的create方法
    def create(self, validated_data):
        request = self.context['request']
        author = request.user
        department_ids = validated_data.pop('department_ids')
        # 对于列表中 所有元素执行相同操作 可以使用map
        department_ids = list(map(lambda value:int(value),department_ids))

        # 查看前端传入的id是否在数据库中存在
        if 0 in department_ids:
            inform = Inform.objects.create(public=True,author=author,**validated_data)
        else:
            departments = OADepartment.objects.filter(id__in=department_ids).all()
            inform = Inform.objects.create(public=False,author=author,**validated_data)
            inform.departments.set(departments)
            inform.save()
        return inform

class ReadInformSerialize(serializers.Serializer):
    inform_pk = serializers.IntegerField(error_messages={"require": '请传入通知信息id'})

    def validate_inform_pk(self,value):
        if not Inform.objects.filter(pk=value).exists():
            raise serializers.ValidationError("请上传正确的通知信息id")
        return value

